package com.wp.controller;

import com.github.pagehelper.PageInfo;
import com.wp.domain.Books;
import com.wp.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 卫鹏
 * @Description
 * @createTime 2021年10月26日 16:26:00
 */
@Controller
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BooksService booksService;

    @RequestMapping("/findAllBooks")
    public ModelAndView findAllBooks(
            @RequestParam(name = "page", required = true, defaultValue = "1") int page,
            @RequestParam(name = "size", required = true, defaultValue = "4") int size) {
        //创建ModelAndView对象:
        ModelAndView mav = new ModelAndView();
        //调用service中的findAll查询所有：
        List<Books> books = booksService.findAll(page,size);
        //创建PageInfo对象：
        PageInfo pageInfo = new PageInfo(books);
        //将数据存储到Request域中:
        mav.addObject("pageInfo", pageInfo);
        mav.setViewName("all-admin-datalist");
        return mav;
    }

    /**
     * 实现路径跳转 到 添加书籍的页面
     */
    @RequestMapping("/btnInBook")
    public String btnInBook() {
        return "addBooks";
    }

    @RequestMapping("/insertBook")
    public String insertBook(Books books) throws ServletException, IOException {
        booksService.insertBook(books);
//        request.getRequestDispatcher("/books/findAllBooks").forward(request, response);
        //使用重定向：
        return "redirect:/books/findAllBooks";
    }

    @RequestMapping("/deleteBook")
    public String deleteBook(@RequestParam(name = "bid", required = false) String bookId) throws ServletException, IOException {
        booksService.deleteBook(bookId);
        //使用重定向：
        return "redirect:/books/findAllBooks";
    }


    /**
     * 添加 此路径 会跳转到updateBook.jsp 提取bookId 封装book数据 到 jsp页面
     */
    @RequestMapping("/btnUpdateBook")
    public String btnUpdateBook(@RequestParam(name = "bookId", required = false) String bookId,
                                Model model) {
        //根据用户提供的id查询book的数据：
        Books book = booksService.findByBookId(bookId);
        //将数据存储到request域中:
        model.addAttribute("book", book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books) throws ServletException, IOException {
        booksService.updateBook(books);
        //使用重定向：
        return "redirect:/books/findAllBooks";
    }


}
